/**
 * 工商申请
 * @author   Liu Yutao <koal@vip.qq.com>
 * @date     2018/3/15 10:24
 */

/**
 * 证件类型隐藏学历、电话、电子邮箱
 * 相应cardType的change事件
 * @param event
 */
function memberCardTypeSwitch(event) {
    var currentForm = $(event.target).parents("form");
    currentForm.find("select[name=cardType]").on('change', function () {
        memberCardTypeSwitchExecute(this, currentForm);
    });
}

/**
 * 证件类型实际执行方法
 */
function memberCardTypeSwitchExecute(thiz, currentForm) {
    if ($(thiz).val() != 1) {
        currentForm.find(".education-box").hide().find("input").attr("disabled", true);
        currentForm.find(".phone-box").hide().find("input").attr("disabled", true);
        currentForm.find(".email-box").hide().find("input").attr("disabled", true);
    } else {
        currentForm.find(".education-box").show().find("input").removeAttr("disabled");
        currentForm.find(".phone-box").show().find("input").removeAttr("disabled");
        currentForm.find(".email-box").show().find("input").removeAttr("disabled");
    }
}


define([
    'jquery',
    'baseUtils',
    'base',
    'msgTool',
    'plugins/bootstrap-dialog/bootstrap-dialog',
    'fileInput',
    'common/pc_camera'
], function ($, baseUtils, base, msgTool, BootstrapDialog) {
    base();

    /**
     * 证件照上传
     * @param rootName      上传css的根节点名字
     * @param cssName       上传css名字
     * @param single        是否单个，true单个，false多个
     * @param filesType     文件类型1文件，0图片
     * @param showCaption   是否显示input框，false隐藏，true显示
     * @param uploadText    按钮文件
     * @param errorCssName  错误css名字
     * @param valName       设置值的节点名字
     * @param showName      展示图的节点名字
     */
    function uploaCard(rootName, cssName, single, filesType, showCaption, uploadText, errorCssName, valName, showName) {
        //节点判断
        var valNode, showNode, errorNode;
        if (rootName !== null) {
            valNode = $(rootName).find(valName);
            showNode = $(rootName).find(showName);
            errorNode = $(rootName).find(errorCssName);
        } else {
            valNode = $(valName);
            showNode = $(showName);
            errorNode = $(errorCssName);
        }
        //上传
        return $.baseUtils.uploader({
            filesType: filesType,
            showCaption: showCaption,
            browseLabel: "选择" + uploadText,
            uploadLabel: "上传",
            rootName: rootName,
            cssName: cssName,
            errorCssName: errorCssName === null ? "#error-message" : errorCssName
        }).on("fileuploaded", function (event, data) {
            if (data.response !== null && data.response.status) {
                if (single) {
                    valNode.val(data.response.url);
                    showNode.html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + data.response.domain + data.response.url + "\" target=\"_blank\"><img src=\"" + data.response.domain + data.response.url + "\"></a></div></div>");
                } else {
                    showNode.append("<div class=\"col-xs-12 col-sm-4 mb15\"><div class=\"thumbnail images-box\"><input type=\"hidden\" name=\"merchantImagesList\" value=\"" + data.response.url + "\"><a href=\"" + data.response.domain + data.response.url + "\" target=\"_blank\"><img src=\"" + data.response.domain + data.response.url + "\"></a></div><div class=\"caption\"><div class=\"btn btn-block btn-danger deletetCover\" onclick=\"$(this).parent().parent().remove()\"><i class=\"iconfont icon-remove\"></i>&nbsp;删除</div></div></div>");
                }
            } else {
                $(errorNode === null ? "#error-message" : errorNode).text(data.response.message);
            }
        });
    }

    //执行
    return {
        /**
         * 基础
         */
        index: function () {

            if (window.isAIO !== undefined && window.isAIO) {
                //删除pc版上传代码
                $("#imagesUploader").remove();
                $("#error-message").remove();
                //添加一体机摄像头代码
                $("#camera_tool_open").html("<label for=\"cardFrontUploader\" class=\"control-label\">请打开高拍仪后，拍摄《租赁合同或房产证》照片，点击确认图片添加资料，可上传多张。</label>" +
                    "<div class=\"col-md-8 alert alert-warning  btn-group btn-group-justified\">" +
                    "<button type='button' class=\"btn btn-default btn-lg open_camera\" data-open-type=\"1\"><i class=\"iconfont icon-paishe\" style=\"font-size:2rem\"></i>&nbsp;打开高拍仪</button>\n" +
                    "<button type='button' class=\"btn btn-default btn-lg confirm_photo\"><i class=\"iconfont icon-paishe\" style=\"font-size:2rem\"></i>&nbsp;确认图片</button>\n" +
                    "<button type='button' class=\"btn btn-default btn-lg btn-block close_camera\"><i class=\"iconfont icon-guanbi\" style=\"font-size:2rem\"></i>&nbsp;关闭高拍仪</button>\n" +
                    "</div>");

            } else {
                //上传执照
                uploaCard(null, "#imagesUploader", false, 0, true, "证照资料", null, null, "#imagesUploadShow");
                if (checkDevice()) {
                    //添加pc高拍仪代码
                    $("#camera_tool_open").html(
                        "<div class=\"col-md-8 alert alert-warning  btn-group btn-group-justified\">" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg \"></a>\n" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg open_camera_pc\"   ><i class=\"iconfont icon-paishe\" style=\"font-size:2rem\"></i>&nbsp;打开高拍仪</a>\n" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg \"></a>\n" +
                        "</div>");
                }

            }


            /**
             * 拍照-事件委托方式
             */
            $("body").on('click', ".confirm_photo", function () {
                //设置消息样式
                msgTool.options = {
                    "positionClass": "toast-bottom-right",
                    "timeOut": "5000"
                };
                send_command(
                    "takePhoto",
                    "nothing",
                    function (receivedData) {
                        var photoBean = JSON.parse(receivedData);
                        if (photoBean.status === 100) {
                            var result = updateBase64('data:image/jpeg;base64,' + photoBean.imgStr);
                            if (result.status) {
                                //添加上传图片
                                $("#imagesUploadShow").append("<div class=\"col-xs-12 col-sm-4 mb15\">\n" +
                                    "<div class=\"thumbnail images-box\"><input type=\"hidden\" name=\"merchantImagesList\" value=\"" + result.url + "\">\n" +
                                    "<img src=\"" + result.domain + result.url + "\">\n" +
                                    "</div>\n" +
                                    "<div class=\"caption\">\n" +
                                    "<div class=\"btn btn-block btn-danger deletetCover\" onclick=\"$(this).parent().parent().remove()\"><i class=\"iconfont icon-remove\"></i>&nbsp;删除</div>\n" +
                                    "</div>\n" +
                                    "</div>");
                                msgTool["success"]("添加资料图片成功", '提示');
                            } else {
                                msgTool["error"](result.message, '提示');
                            }


                        } else if (photoBean.status === 300) {
                            msgTool["error"]('模块未开启', '提示');
                        } else if (photoBean.status === 200) {
                            msgTool["error"]('拍照关闭失败：' + photoBean.msg, '提示');
                        }
                    }
                );
            });

            /**
             * 打开pc高拍仪
             */
            $("body").on('click', ".open_camera_pc", function () {

                // 调用show方法
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    title: '高拍仪 ',
                    message: '<object id="view"  type="application/x-eloamplugin" width="560" height="400"   name="view"   ></object>',
                    buttons: [{
                        label: '拍照',
                        cssClass: 'btn-primary',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            Scan("#imagesUploadShow", "merchantImagesList");
                        }
                    }, {
                        label: '关闭',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            dialog.close();  //返回验证结果
                        }
                    }],
                    onshown: function () {
                        Load();
                    },
                    onhide: function () {
                        CloseVideo();
                    }
                });

            });


            /**
             * 返回列表
             */
            $("#retrunUserIndex").on('click', function () {
                if (window.isAIO !== undefined && window.isAIO) {
                    closeCamera();
                }
                window.location = "/user/index";
            });

            /**
             * 提交下一步
             */

            $("#doSubmit").on('click', function () {
                if (window.isAIO !== undefined && window.isAIO) {
                    closeCamera();
                }
                var valid = $("#merchantIndexForm").valid();
                if (valid) {
                    $.ajax({
                        url: "/merchantApply/save",
                        type: 'POST',
                        data: $("#merchantIndexForm").serialize(),
                        dataType: "JSON",
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            $("#doSubmit").text('提交中...');
                            $("#doSubmit").attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                window.location.href = "/merchantApply/member/" + data.model.id;
                            } else {
                                $("#messageCode").text(data.msg);
                            }
                        },
                        error: function (error) {
                            console.log(error);
                            $("#messageCode").text("登录注册，请刷新页面后重试！");
                        },
                        complete: function () {
                            $("#doSubmit").text("下一步");
                            $("#doSubmit").removeAttr('disabled');
                        }
                    });
                }
            });
        },

        /**
         * 经营者
         */
        member: function () {

            if (window.isAIO !== undefined && window.isAIO) {

                $("#camera_tool_open").html("<div class=\"alert alert-warning btn-group btn-group-justified\">\n" +
                    "<button type='button'  class=\"btn btn-default btn-lg open_camera\" data-open-type=\"2\"><i class=\"iconfont icon-paishe\" style=\"font-size:2rem\"></i>&nbsp;打开高拍仪</button>\n" +
                    "<button type='button'  class=\"btn btn-default btn-lg close_camera\"><i class=\"iconfont icon-guanbi\" style=\"font-size:2rem\"></i>&nbsp;关闭高拍仪</button>\n" +
                    "</div>");

                $(".upload-tips").html("打开高拍仪，并放置当前经营者的证件，点击确认添加按钮即可。");

                $("#cardFrontPicture").next(".input-group-btn").html("<button type=\"button\" class=\"btn btn-success btn-outline confirm_photo\">确认正面照</button>");

                $("#cardBackPicture").next(".input-group-btn").html("<button type=\"button\" class=\"btn btn-success btn-outline confirm_photo\">确认背面照</button>");

            } else {

                //证件正面照
                uploaCard(null, "#cardFrontUploader", true, 0, false, "正面照", "#front-error-message", "#cardFrontPicture", "#cardFrontPictureShow");
                //证件反面照
                uploaCard(null, "#cardBackUploader", true, 0, false, "反面照", "#back-error-message", "#cardBackPicture", "#cardBackPictureShow");
                if (checkDevice()) {
                    //添加pc高拍仪代码
                    $("#camera_tool_open").html(
                        "<div class=\"col-md-8 alert alert-warning  btn-group btn-group-justified\">" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg \"></a>\n" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg open_idcard_pc\"><i class=\"iconfont icon-gerenziliao\" style=\"font-size:2rem\"></i>&nbsp;身份证读取</a>\n" +
                        "<a href=\"#\" class=\"btn btn-default btn-lg \"></a>\n" +
                        "</div>");
                }

            }


            /**
             * 拍照-事件委托方式
             */
            $("body").on('click', ".confirm_photo", function () {
                var button = $(this);
                //设置消息样式
                msgTool.options = {
                    "positionClass": "toast-bottom-right",
                    "timeOut": "5000"
                };
                send_command(
                    "takePhoto",
                    "nothing",
                    function (receivedData) {
                        var photoBean = JSON.parse(receivedData);
                        if (photoBean.status === 100) {
                            var result = updateBase64('data:image/jpeg;base64,' + photoBean.imgStr);
                            if (result.status) {
                                $(button).parent().prev('input').val(result.url);
                                $(button).parents("div.form-group").find("img").attr("src", result.domain + result.url);
                                msgTool["success"](button.text() + "成功", '提示');
                            } else {
                                msgTool["error"](result.message, '提示');
                            }
                        } else if (photoBean.status === 300) {
                            msgTool["error"]('模块未开启', '提示');
                        } else if (photoBean.status === 200) {
                            msgTool["error"]('拍照关闭失败：' + photoBean.msg, '提示');
                        }
                    }
                );
            });


            /**
             * 高拍仪身份证读取
             * */

            $(".open_idcard_pc").on('click', function () {
                var obj = ReadIDCard();
                $("#name").val(obj.name);
                if (obj.sex == '男') {
                    $("#sex1").attr("checked", true);
                } else if (obj.sex == '女'){
                    $("#sex2").attr("checked", true);
                }
                $("#nation").find("option[text='" + obj.nation + "']").attr("selected", true);
                $("#cardType").val(1);
                $("#cardNumber").val(obj.idcard);
                $("#nation").val(obj.nation);
                $("#address").val(obj.address);
                
         		var result = updateBase64('data:image/jpeg;base64,' + obj.IDcard_frontImg_base64);
         		if (result.status) {
         			$("#cardFrontPicture").val(result.url);
         			$("#cardFrontPictureShow").html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + result.domain + result.url + "\" target=\"_blank\"><img src=\"" + result.domain + result.url + "\"></a></div></div>");
         		} else {
         			obj.message=result.message;
         		}	

         		
        		var result = updateBase64('data:image/jpeg;base64,' + obj.IDcard_backImg_base64);
        		if (result.status) {
        			$("#cardBackPicture").val(result.url);
        		    $("#cardBackPictureShow").html("<div class=\"mb15 mt15\"><div class=\"thumbnail images-box\"><a href=\"" + result.domain + result.url + "\" target=\"_blank\"><img src=\"" + result.domain + result.url + "\"></a></div></div>");
        		} else {
        			obj.message=result.message;
        		}	
                
                if (obj.message != null) {
                    msgTool["error"](obj.message, '提示');
                } else {
                    msgTool["success"]('身份证读取成功！', '提示');
                }

            });



            /**
             * 提交添加
             */
            $("#doSubmit").on('click', function () {
                    var dataFormStatus = $("#memeberForm").valid();
                    if (dataFormStatus) {
                        $.ajax({
                            url: "save.json",
                            type: 'POST',
                            data: $("#memeberForm").serialize(),
                            dataType: "JSON",
                            beforeSend: function () {
                                //触发ajax请求开始时执行
                                $("#doSubmit").text('提交中...');
                                $("#doSubmit").attr('disabled', 'disabled');
                            },
                            success: function (data) {
                                if (data.success) {
                                    window.location.href = "/merchantApply/success/" + $('#applyId').val();
                                } else {
                                    $("#messageCode").text(data.msg);
                                }
                            },
                            error: function () {
                                $("#messageCode").text("保存失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("下一步");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );

        },


        /**
         * 申请成功
         */
        success: function () {
            console.log("申请成功.js。。。。。");
        }
    };
});
